import os
import re
import datetime
import logging
from django.http import HttpResponseServerError
import translate
from google.appengine.ext import db


def get_slug(title):
    slug =  get_friendly_url(translate.translate('zh-CN','en', u(title,'utf-8')))
    if not slug:
        return HttpResponseServerError()    

    search_blog = db.GqlQuery("select * from Post where slug >= :1 and slug < :2 order by slug desc",slug, slug+u"\xEF\xBF\xBD").get()
    if search_blog is not None:
        slug = search_blog.slug+"i"
    return slug

def get_friendly_url(title):
    return re.sub('-+', '-', re.sub('[^\w-]', '', re.sub('\s+', '-', removepunctuation(title).strip()))).lower()

def removepunctuation(str):
    punctuation = re.compile(r'[.?!,":;]')
    str = punctuation.sub("", str)
    return str

def u(s, encoding):
    if isinstance(s, unicode):
        return s
    else:
        return unicode(s, encoding)